//
//  Tools.swift
//  Tools
//
//  Created by Felix Yuan on 2020/3/3.
//  Copyright © 2020 Hangzhou Shichuo Information Technology Co, Ltd. All rights reserved.
//

import Foundation
import CryptoSwift

public func md5File(url: URL) -> String? {
    let bufferSize = 1024 * 10240
    do {
        let file = try FileHandle(forReadingFrom: url)
        defer {
            file.closeFile()
        }

        var md5 = MD5()
        while autoreleasepool(invoking: {
            let data = file.readData(ofLength: bufferSize)
            if !data.isEmpty {
                var bytes: [UInt8] = []
                data.withUnsafeBytes {
                    bytes.append(contentsOf: $0)
                }
                do {
                    _ = try md5.update(withBytes: bytes)
                } catch {}
                return true
            } else {
                return false
            }
        }) {}

        do {
            let bytes = try md5.finish()
            let length = bytes.count
            return (0 ..< length).reduce("") {
                $0 + String(format: "%02x", bytes[$1])
            }
        } catch {}
        return nil
    } catch {}
    return nil
}

public func isTestFlight() -> Bool {
    guard let appstoreReceiptURL = Bundle.main.appStoreReceiptURL else {
        return false
    }
    return appstoreReceiptURL.lastPathComponent == "sandboxReceipt"
}

